#!/bin/bash

# Finder 跳转到 iTerm 脚本
# 获取当前 Finder 窗口的路径并在 iTerm 中打开

get_finder_path() {
    # 获取当前 Finder 窗口的路径
    local path=$(osascript -e '
    tell application "Finder"
        if (count of windows) > 0 then
            set current_folder to (target of front window) as alias
            return POSIX path of current_folder
        else
            return ""
        end if
    end tell
    ' 2>/dev/null)
    
    # 如果获取失败，使用默认路径
    if [ -z "$path" ] || [ "$path" = "missing value" ]; then
        path="$HOME"
    fi
    
    echo "$path"
}

open_in_iterm() {
    local target_path="$1"
    
    osascript -e "
    tell application \"iTerm\"
        activate
        if (count of windows) = 0 then
            create window with default profile
        end if
        
        tell current session of current window
            write text \"cd \" & quoted form of \"$target_path\"
        end tell
    end tell
    "
}

# 主执行逻辑
main() {
    local current_path=$(get_finder_path)
    echo "当前 Finder 路径: $current_path"
    
    open_in_iterm "$current_path"
    echo "已在 iTerm 中打开: $current_path"
}

main "$@"